import React, { Component } from 'react'


import {createStore} from 'redux'

// 默认状态
let defaultState = {
  count: 0
}
// reducers
function reducers(state = defaultState, action) {
  console.log(action)
  switch(action.type) {
    case 'add':
      return {
        ...state,
        count: state.count+action.val
        
      }
    default:
      return state
  }
}

//创建store
let store = createStore(reducers);

export default class MyComp extends Component {
  componentDidMount() {
    store.subscribe(() => {
      this.setState({})
    })
  }

  addHandler = () => {
    store.dispatch({
      type: 'add',
      val: 2
    })
  }

  requsetHandler = () => {
    fetch("http://localhost:4000/api/citylist")
      .then(res => res.json())
      .then(res => {
        store.dispatch({type: 'request', data: res})
      })
  }
  render() {
    let {count} = store.getState()
    return (
      <div>
        <h2>{count}</h2>
        <button onClick={this.addHandler}>add</button>
        <h2>{1}</h2>
        <button onClick={this.requsetHandler}>request</button>
      </div>
    )
  }
}
